package net.caixiaomi.info.ui.football.detail;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.sobot.chat.utils.DateUtil;

import net.caixiaomi.info.R;
import net.caixiaomi.info.adapter.CommonFragmentPageAdapter;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.CommonTab;
import net.caixiaomi.info.model.MatchInfoForTeam;
import net.caixiaomi.info.model.MatchIntroduceModel;
import net.caixiaomi.info.model.MatchItem;
import net.caixiaomi.info.model.MatchLineupModel;
import net.caixiaomi.info.model.MatchLiveModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.ToastUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import retrofit2.Call;

/**
 * 查看详情
 */
public class MatchDetailActivity extends BaseActivity {
    @BindView(R.id.time)
    TextView mTime;
    @BindView(R.id.icon_host)
    ImageView mIconHost;
    @BindView(R.id.host)
    TextView mHost;

    @BindView(R.id.match_detail_title_bottom_tv)
    TextView mBottomTv;
    @BindView(R.id.match_detail_title_left_tv)
    TextView mLeftTv;
    @BindView(R.id.match_detail_title_center_tv)
    TextView mCenterTv;
    @BindView(R.id.match_detail_title_right_tv)
    TextView mRightTv;

    @BindView(R.id.icon_guest)
    ImageView mIconGuest;
    @BindView(R.id.guest)
    TextView mGuest;
    @BindView(R.id.tab)
    TabLayout mTabLayout;
    @BindView(R.id.pager)
    ViewPager mViewPager;
    @BindView(R.id.appbar)
    AppBarLayout mAppBarLayout;
    @BindView(R.id.progress)
    CircularProgressBar mProgress;
    @BindView(R.id.container)
    View mContainer;

    private CommonFragmentPageAdapter mAdapter;
    private AnalysisFragment mAnalysisFragment;
    private OddsFragment mOddsFragment;
    private MatchLiveFragment mLiveFragment;
    private MatchTeamFragment mTeamFragment;
    private String mMatchId = "";
    private int mPosition = 1;

    private Disposable loadDataTimerDis;
    private int interValTime=60*1000;

    @Override
    protected int layout() {
        return R.layout.act_match_detail;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMatchId = getIntent().getStringExtra("data");
        String[] tabArray = getResources().getStringArray(R.array.TAB_MATCH_INFO);

        boolean dealVersion = CommonApp.STORE.getBoolean(Constants.KEY_DEAL_VERSION, false);
//        dealVersion=true;

        List<Fragment> data = new ArrayList<>();
        List<CommonTab> titles = new ArrayList<>();
        for (int index = 0; index < tabArray.length; index++) {
            CommonTab tab = new CommonTab(index, tabArray[index]);
//            if (index == 0) {
                titles.add(tab);
//            }

            switch (index){
                case 0:
                    mLiveFragment = new MatchLiveFragment();
                    break;
                case 1:
                    mAnalysisFragment = new AnalysisFragment();
                    break;
                case 2:
                    mOddsFragment = new OddsFragment();
                    break;
                case 3:
                    mTeamFragment = new MatchTeamFragment();
                    break;
            }

        }
        data.add(mLiveFragment);
        data.add(mAnalysisFragment);
        data.add(mOddsFragment);
        data.add(mTeamFragment);

        if(!dealVersion&&getString(R.string.NORMAL_PACKAGE).equals("1")){
            data.remove(mOddsFragment);
            titles.remove(2);
        }

        mAdapter = new CommonFragmentPageAdapter(getSupportFragmentManager(), titles, data);
        mViewPager.setAdapter(mAdapter);
        mViewPager.setOffscreenPageLimit(4);
        mTabLayout.setupWithViewPager(mViewPager);//将TabLayout和ViewPager关联起来。
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        LinearLayout linearLayout = (LinearLayout) mTabLayout.getChildAt(0);
        linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        linearLayout.setDividerDrawable(ContextCompat.getDrawable(this, R.drawable.layout_divider_vertical));
//        mViewPager.addOnPageChangeListener(mChangeListener);
        mViewPager.setCurrentItem(mPosition);
        if(getResources().getColor(R.color.bar_background_color)==getResources().getColor(R.color.orange_primary)){
            mToolbar.setBackgroundColor(ContextCompat.getColor(CommonApp.getInstance(), R.color.bar_background_color));
            otherApp=true;
        }
        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (!otherApp) {
                    if (verticalOffset == 0) {//展开
                        mToolbar.setBackgroundColor(Color.argb((int) 0, 0, 0, 0));
                    } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {//折叠
                        mToolbar.setBackgroundColor(ContextCompat.getColor(CommonApp.getInstance(), R.color.background));
                    } else {//中间状态
                        mToolbar.setBackgroundColor(Color.argb((int) 0, 0, 0, 0));
                    }
                }
            }
        });

        loadData();
        loadMatchLive();
        startTimerTask();
        loadMatchTeamLive();
        loadMatchLive();

    }


    boolean otherApp=false;
    private void loadData() {
        JSONObject params = new JSONObject();
        params.put("matchId", mMatchId);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<MatchIntroduceModel>> baseCallModelCall = requestService.matchTeamInfos(params);
        baseCallModelCall.enqueue(new ResponseCallback<BaseCallModel<MatchIntroduceModel>>(this) {
            @Override
            public void onSuccess(BaseCallModel<MatchIntroduceModel> data) {
                MatchIntroduceModel model = data.data;
                mContainer.setVisibility(View.VISIBLE);
                mProgress.setVisibility(View.GONE);
                mLiveFragment.setMatchDetailData(model);
                bindData(model);
            }


            @Override
            public void onFail(ResponseError error) {
                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                    ToastUtil.s(error.getMessage());
                }
            }

            @Override
            public void onError() {

            }
        });

    }

    private void bindData(MatchIntroduceModel model) {
        try {
            boolean dealVersion = CommonApp.STORE.getBoolean(Constants.KEY_DEAL_VERSION, false);
//            dealVersion=true;
            StringBuilder stringBuilder = new StringBuilder();
            MatchInfoForTeam matchInfo = model.getMatchInfo();
            RequestOptions options = new RequestOptions();
            options.error(R.mipmap.ic_football);
            options.placeholder(R.mipmap.ic_football);
            Glide.with(this).load(matchInfo.getHomeTeamPic()).apply(options).into(mIconHost);
            Glide.with(this).load(matchInfo.getVisitingTeamPic()).apply(options).into(mIconGuest);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String time = sdf.format(new Date(Long.parseLong(matchInfo.getMatchTime()) * 1000));

            stringBuilder.append(matchInfo.getChangci()).append("  ").append(matchInfo.getLeagueAddr()).append("  ").append(time);
            mTime.setText(stringBuilder);

            stringBuilder.setLength(0);
            if (!TextUtils.isEmpty(matchInfo.getHomeTeamRank())) {
                stringBuilder.append("[").append(matchInfo.getHomeTeamRank()).append("]");
            }
            stringBuilder.append(matchInfo.getHomeTeamAbbr());
            String homeTeam = stringBuilder.toString();
            stringBuilder.setLength(0);
            stringBuilder.append(homeTeam);
            SpannableString spannableString = new SpannableString(stringBuilder);
            mHost.setText(spannableString);

            stringBuilder.setLength(0);
            if (!TextUtils.isEmpty(matchInfo.getVisitingTeamRank())) {
                stringBuilder.append("[").append(matchInfo.getVisitingTeamRank()).append("]");
            }
            stringBuilder.append(matchInfo.getVisitingTeamAbbr());
            String visitTeam = stringBuilder.toString();
            stringBuilder.setLength(0);
            stringBuilder.append(visitTeam);
            spannableString = new SpannableString(stringBuilder);
            mGuest.setText(spannableString);

            mAnalysisFragment.setData(model);
            mOddsFragment.setData(model);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void loadMatchTeamLive(){
        JSONObject params = new JSONObject();
        params.put("matchId", mMatchId);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<MatchLineupModel>> baseCallModelCall = requestService.getMatchLineupInfo(params);
        baseCallModelCall.enqueue(new ResponseCallback<BaseCallModel<MatchLineupModel>>() {
            @Override
            public void onSuccess(BaseCallModel<MatchLineupModel> data) {

                mTeamFragment.setData(data.data);
            }

            @Override
            public void onFail(ResponseError error) {

            }

            @Override
            public void onError() {

            }
        });
    }

    public void loadMatchLive(){
        JSONObject params = new JSONObject();
        params.put("matchId", mMatchId);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<MatchLiveModel>> baseCallModelCall = requestService.getMatchLiveInfo(params);
        baseCallModelCall.enqueue(new ResponseCallback<BaseCallModel<MatchLiveModel>>() {
            @Override
            public void onSuccess(BaseCallModel<MatchLiveModel> data) {
                mLiveFragment.setData(data.data);
                bindMatchLive(data.data);
            }

            @Override
            public void onFail(ResponseError error) {
                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                    ToastUtil.s(error.getMessage());
                }
            }

            @Override
            public void onError() {

            }
        });

    }

    private void bindMatchLive(MatchLiveModel model){

        try {
            if(!TextUtils.isEmpty(model.getMatchStatus())){
                int matchStatus=Integer.parseInt(model.getMatchStatus());
                String[] statusList = getResources().getStringArray(R.array.C_MATCH_STATUS);
                mCenterTv.setText(statusList[matchStatus]);
                long time=Long.parseLong(model.getMatchTime())*1000;
                Date d = new Date(time);
                SimpleDateFormat sdf =DateUtil.DATE_FORMAT6;
                if(matchStatus==6){
                    mCenterTv.setText(model.getMinute()+"′");
                }

                switch (matchStatus){
                    case 0: //未开赛
                        mLeftTv.setText("");
                        mRightTv.setText("");
                        mBottomTv.setText(sdf.format(d));
                        break;
                    case 2: //取消
                    case 4: //推迟
                        mLeftTv.setText("");
                        mRightTv.setText("");
                        mBottomTv.setText(sdf.format(d));
                        break;
                    case 1: //已完成
                    case 5: //暂停
                    case 6: //进行中
                        String fsA=model.getFsA();
                        String fsH=model.getFsH();
                        String htsA=model.getHtsA();
                        String htsH=model.getHtsH();
                        mLeftTv.setText(fsH);
                        mRightTv.setText(fsA);
                        mBottomTv.setText("半场 "+htsH+":"+htsA);
                        break;
                }
            }
        }catch (Exception e){

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelTimerTask();
    }


    public void startTimerTask(){

        setInterValLoadData(interValTime, new IRxNext() {
            @Override
            public void doNext(long number) {
                loadMatchLive();
            }
        });
    }

    private void setInterValLoadData(long milliseconds,final IRxNext next){
        Observable.interval(milliseconds, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable disposable) {
                        loadDataTimerDis=disposable;
                    }

                    @Override
                    public void onNext(@NonNull Long number) {
                        if(next!=null){
                            next.doNext(number);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public interface IRxNext{
        void doNext(long number);
    }

    public void cancelTimerTask(){
        if(loadDataTimerDis!=null&&!loadDataTimerDis.isDisposed()){
            loadDataTimerDis.dispose();
        }
    }

}
